package com.ucode.application.controller.crm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.application.form.crm.BusinessForm;
import com.ucode.application.helper.CrmDataPermissionVerifier;
import com.ucode.application.security.CurrentLoginUserService;
import com.ucode.application.vo.crm.FollowupTeamUserVo;
import com.ucode.crm.dictionary.CrmResultDefineMsg;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.dictionary.TeamUserPower;
import com.ucode.crm.mode.Business;
import com.ucode.crm.mode.Customer;
import com.ucode.crm.mode.CrmTeamUser;
import com.ucode.crm.service.BusinessService;
import com.ucode.crm.service.CustomerService;
import com.ucode.crm.vo.BusinessVo;
import com.ucode.search.crm.model.ESBusiness;
import com.ucode.search.crm.service.ESBusinessService;
import com.ucode.crm.service.CrmTeamUserService;
import com.ucode.springboot.starter.web.validator.group.AddGroup;
import com.ucode.springboot.starter.web.validator.group.UpdateGroup;
import com.ucode.sys.model.User;
import com.ucode.sys.service.UserService;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="CRM-商机")
@RestController
@RequestMapping("/crm-business")
@Validated
public class BusinessController {
    
    private static final String moduleCode = "crm";
    @Autowired
    private BusinessService businessService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CrmTeamUserService crmTeamUserService;
    @Autowired
    private CurrentLoginUserService currentLoginUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private CrmDataPermissionVerifier dataPermissionVerifier;
    @Autowired
    private ESBusinessService esBusinessService;

    @PreAuthorize("hasAuthority('crm:business:list') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation("列表")
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(
            @ApiParam(value ="客户名称/电话/手机号",required=false)  @RequestParam(value = "keywords",required=false) String keyword,
            @ApiParam(value ="用户(最多20人)",required=false)  @Size(max = 20,message="一次最多选择20人")@RequestParam(value = "userIds",required=false) List<Long> userIds,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        userIds = dataPermissionVerifier.getCheckCurrentUserManageUsers(moduleCode, userIds);
        try {
            Paginator<ESBusiness> paginator = esBusinessService.searchByUser(userIds, keyword, pageNum, pageSize);
            Paginator<BusinessVo> vopag = new Paginator<>(paginator.getTotal(), paginator.getCurrentPage(), paginator.getRows());
            if(paginator != null && CollUtil.isNotEmpty(paginator.getList())){
                List<ESBusiness> list = paginator.getList();
                List<Long> ids = new ArrayList<Long>();
                Set<Long> _userIds = new HashSet<Long>(); 
                for(ESBusiness esBusiness : list){
                    ids.add(esBusiness.getId());
                    _userIds.add(esBusiness.getCreateUserId());
                    _userIds.add(esBusiness.getOwnerUserId());
                }
                
                CompletableFuture<Map<Long, BusinessVo>> completableFutureBusinessVos = CompletableFuture.supplyAsync(() -> {
                    try {
                        List<BusinessVo> _list = businessService.findVoByIds(ids);
                        Map<Long, BusinessVo> map = _list.stream().collect(Collectors.toMap(BusinessVo::getId,Function.identity(),(key1, key2) -> key1));
                        return map;
                    } catch (Exception e) {
                    }
                    return new HashMap<>();
                });
                
                CompletableFuture<Map<Long, String>> completableFutureUser = CompletableFuture.supplyAsync(() -> {
                    try {
                        List<User> ulist = userService.findByIds(new ArrayList<>(_userIds));
                        Map<Long, String> customerMap = ulist.stream().collect(Collectors.toMap(User::getId,User::getRealname,(key1, key2) -> key1));
                        return customerMap;
                    } catch (Exception e) {
                    }
                    return new HashMap<>();
                });
                
                Map<Long, BusinessVo> bMap = completableFutureBusinessVos.get();
                Map<Long, String> uMap = completableFutureUser.get();
                
                List<BusinessVo> vos = new ArrayList<>();
                for(ESBusiness esBusiness : list){
                    BusinessVo businessVo = bMap.get(esBusiness.getId());
                    if(businessVo !=null){
                        businessVo.setCreateUser(uMap.get(esBusiness.getCreateUserId()));
                        businessVo.setOwnerUser(uMap.get(esBusiness.getOwnerUserId()));
                        vos.add(businessVo);
                    }
                }
                vopag.setList(vos); 
            }
            return ResponseResult.success(vopag);
        } catch (Exception e) {
            throw new UcodeServiceException(ResultCodeEnum.SERVER_ERROR);
        }
    }
    
    
    @PreAuthorize("hasAuthority('crm:business:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="根据主键查询")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/getById/{id}")
    public ResponseResult<Object> getById(@PathVariable(name="id",required=true) Long id){
        
        BusinessVo business = businessService.findVoById(id);
        if(business == null || business.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        
        List<Long> ownerUserIds = Arrays.asList(business.getOwnerUserId(),business.getCownerUserId());
        dataPermissionVerifier.getCurrentUserPowerByBusinessData(moduleCode, ModuleType.business, business.getId(), ownerUserIds);
        
        return ResponseResult.success(business);
    }
    
    @PreAuthorize("hasAuthority('crm:business:detail') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="详情信息")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/detail/{id}")
    public ResponseResult<Object> detail(@PathVariable(name="id",required=true) Long id){
        
        BusinessVo business = businessService.findVoById(id);
        if(business == null || business.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        
        List<Long> ownerUserIds = Arrays.asList(business.getOwnerUserId(),business.getCownerUserId());
        Integer power = dataPermissionVerifier.getCurrentUserPowerByBusinessData(moduleCode, ModuleType.business, business.getId(), ownerUserIds);
        business.setPower(power);
        
        List<Long> userIds = Arrays.asList(business.getOwnerUserId(),business.getCreateUserId());
        List<User> users = userService.findByIds(userIds);
        if(CollUtil.isNotEmpty(users)){
            Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId,Function.identity(),(key1, key2) -> key1));
            User createUser = userMap.get(business.getCreateUserId());
            business.setCreateUser(createUser!=null?createUser.getRealname():null);
            User ownerUser = userMap.get(business.getOwnerUserId());
            business.setOwnerUser(ownerUser!=null?ownerUser.getRealname():null);
        }
        
        return ResponseResult.success(business);
    }
    
    
    @PreAuthorize("hasAuthority('crm:business:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="创建")
    @PostMapping("/create")
    public ResponseResult<Object> create(@Validated({AddGroup.class}) @RequestBody BusinessForm form) {
        
        Customer customer = customerService.findById(form.getCustomerId());
        if(customer == null || customer.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD.code,CrmResultDefineMsg.contacts_add_business_deleted_error);
        }
        
        if(customer == null || customer.getOwnerUserId().equals(0L)){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_add_business_error);
        }
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        Business business = form.build();
        business.setStageState(0);
        business.setCreateUserId(currentUserId);
        business.setOwnerUserId(currentUserId);
        business.setCownerUserId(customer.getId());
        
        business = businessService.insert(business);
        
        return business != null ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:business:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="更新")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/update/{id}")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
            @Validated({UpdateGroup.class}) @RequestBody BusinessForm form) {
        
        Business dbbusiness = businessService.findById(id);
        if(dbbusiness == null || dbbusiness.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        //赢单结束
        if(dbbusiness.getStageState().intValue() == 1){
            throw new UcodeServiceException(ResultCodeEnum.VALIDATE_FAILED.code,CrmResultDefineMsg.business_end_edit_error);
        }
        /**
         * 商机负责人与商机所属的客户负责人拥有相同的数据权限
         */
        List<Long> ownerUserIds = Arrays.asList(dbbusiness.getOwnerUserId(),dbbusiness.getCownerUserId());
        
        //校验数据编辑权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, dbbusiness.getId(), ownerUserIds, CrmResultDefineMsg.business_edit_permission_error, dbbusiness.getName());
        
        Business business = form.build();
        business.setId(id);
        business.setStageState(0);
        
        int i = businessService.update(business);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:business:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="商机推进")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/advance/{id}")
    public ResponseResult<Object> advance(@PathVariable(name="id",required=true) Long id,
            @ApiParam(value="阶段Id",required=true)@RequestParam(value = "statusId", required=true) Long statusId) {
        
        Business dbbusiness = businessService.findById(id);
        if(dbbusiness == null || dbbusiness.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        //赢单结束
        if(dbbusiness.getStageState().intValue() == 1){
            throw new UcodeServiceException(ResultCodeEnum.VALIDATE_FAILED.code,CrmResultDefineMsg.business_end_edit_error);
        }
        /**
         * 商机负责人与商机所属的客户负责人拥有相同的数据权限
         */
        List<Long> ownerUserIds = Arrays.asList(dbbusiness.getOwnerUserId(),dbbusiness.getCownerUserId());
        
        //校验数据编辑权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, dbbusiness.getId(), ownerUserIds, CrmResultDefineMsg.business_edit_permission_error, dbbusiness.getName());
        
        Business business = new Business();
        business.setId(id);
        business.setStatusId(statusId);
        business.setStageState(0);
        int i = businessService.update(business);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:business:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="商机结束")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/end/{id}")
    public ResponseResult<Object> end(@PathVariable(name="id",required=true) Long id,
            @ApiParam(value="结束状态:1赢单2输单3无效",required=true)@RequestParam(value = "stageState", required=true) Integer stageState,
            @ApiParam(value="结束备注",required=true)@RequestParam(value = "endRemark", required=false) String endRemark) {
        
        Business dbbusiness = businessService.findById(id);
        if(dbbusiness == null || dbbusiness.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        //赢单结束
        if(dbbusiness.getStageState().intValue() == 1){
            throw new UcodeServiceException(ResultCodeEnum.VALIDATE_FAILED.code,CrmResultDefineMsg.business_end_edit_error);
        }
        /**
         * 商机负责人与商机所属的客户负责人拥有相同的数据权限
         */
        List<Long> ownerUserIds = Arrays.asList(dbbusiness.getOwnerUserId(),dbbusiness.getCownerUserId());
        
        //校验数据编辑权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, dbbusiness.getId(), ownerUserIds, CrmResultDefineMsg.business_edit_permission_error, dbbusiness.getName());
        
        Business business = new Business();
        business.setId(id);
        business.setStageState(stageState);
        int i = businessService.update(business);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:business:delete') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="删除")
    @PostMapping("/delete")
    public ResponseResult<Object> delete(
            @ApiParam(value="Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        List<Business> businesses = businessService.findByIds(ids);
        if(CollUtil.isNotEmpty(businesses)){
             for(Business business : businesses){
                if(business.getDeltag() == 1)
                    continue;
                 
                List<Long> ownerUserIds = Arrays.asList(business.getOwnerUserId(),business.getCownerUserId());
                //校验权限
                dataPermissionVerifier.checkCurrentUserOwnerPowerByBusinessData(moduleCode, ModuleType.business, ownerUserIds, CrmResultDefineMsg.business_delete_permission_error, business.getName());
                
                customerService.deleteByLogic(business.getId());
            }
        }
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:business:transfer') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="转移")
    @PostMapping("/transfer")
    public ResponseResult<Object> transfer(
            @ApiParam(value="商机Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids,
            @ApiParam(value="新负责人",required=true) @RequestParam(value = "ownerUserId", required=true) Long ownerUserId,
            @ApiParam(value="将原负责人:0->移除;1->转为团队成员",required=true) @RequestParam(value = "optType", required=true) Integer optType,
            @ApiParam(value="原负责人转为团队成员后的权限:1->只读2->读写(optType为1时必传)",required=false) @RequestParam(value = "power", required=false)Integer power,
            @ApiParam(value="同步转移(0->联系人1-商机2->合同)",required=false) @RequestParam(value = "changeModules", required=false)List<Integer> changeModules) {
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        List<Business> businesses = businessService.findByIds(ids);
        if(CollUtil.isNotEmpty(businesses)){
            for(Business business : businesses){
                List<Long> ownerUserIds = Arrays.asList(business.getOwnerUserId(),business.getCownerUserId());
                //校验权限
                dataPermissionVerifier.checkCurrentUserOwnerPowerByBusinessData(moduleCode, ModuleType.business, ownerUserIds, CrmResultDefineMsg.business_transfer_permission_error, business.getName());
                
                int i = businessService.transfer(business.getId(), ownerUserId, currentUserId);
                //将原负责人变为团队成员，如果重新加入团队异常,直接忽略
                if(i > 0 && optType.equals(1)){
                    crmTeamUserService.batchInsert(business.getId(), ModuleType.business.code, Arrays.asList(ownerUserId), power.intValue() == 2 ?TeamUserPower.readWrite.code:TeamUserPower.read.code);
                 }
            }
        }
        
        return ResponseResult.success();
    }
    
    @ApiOperation(value="查询跟进团队成员")
    @ApiImplicitParam(name = "targetId", value = "商机ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/teamUsers/{targetId}")
    public ResponseResult<Object> getTeamUsers(@PathVariable(name="targetId",required=true) Long targetId){
        
        List<CrmTeamUser> followupTeamUsers = crmTeamUserService.findList(targetId, ModuleType.business.code);
        List<FollowupTeamUserVo> followupTeamUserVos = new ArrayList<>();
        if(CollUtil.isNotEmpty(followupTeamUsers)){
            List<Long> userIds =followupTeamUsers.stream().map(m -> m.getUserId()).distinct().collect(Collectors.toList());
            List<User> users = userService.findByIds(userIds);
            Map<Long, User> userMap = null;
            if(CollUtil.isNotEmpty(users)){
                userMap = users.stream().collect(Collectors.toMap(User::getId,Function.identity(),(key1, key2) -> key2));
            }
            
            for(CrmTeamUser followupTeamUser : followupTeamUsers){
                User user = userMap != null ? userMap.get(followupTeamUser.getUserId()) : null;
                followupTeamUserVos.add(new FollowupTeamUserVo(followupTeamUser, user));
            }
            
        }
        
        return ResponseResult.success(followupTeamUserVos);
    }
    
    @PreAuthorize("hasAuthority('crm:business:editTeamUser') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="添加跟进团队成员")
    @PostMapping("/teamUser/add")
    public ResponseResult<Object> addTeamUser(
            @ApiParam(value="商机Id",required=true)@RequestParam(value = "targetId", required=true) Long targetId,
            @ApiParam(value="成员Ids",required=true) @Size(min = 1,max=20,message="一次添加1-20人")@RequestParam(value = "userIds", required=true) List<Long> userIds,
            @ApiParam(value = "权限类型:0、负责人权限(读写)1、读写权限2、只读权限",required=true,example="2") @RequestParam(value = "power", required=true)Integer power) {
        
        Business business = businessService.findById(targetId);
        if(business == null || business.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        List<Long> ownerUserIds = Arrays.asList(business.getOwnerUserId(),business.getCownerUserId());
        //校验权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.business, business.getId(), ownerUserIds, CrmResultDefineMsg.teamUser_add_permission_error);
        
        //不能添加为负责人权限
        if(TeamUserPower.readWrite.code != power){
            power = TeamUserPower.read.code;
        }
        
        crmTeamUserService.batchInsert(business.getId(), ModuleType.business.code, userIds, power);     
        
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:business:editTeamUser') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="编辑跟进团队成员")
    @PostMapping("/teamUser/update")
    public ResponseResult<Object> updateTeamUser(
            @ApiParam(value="团队成员关系Id",required=true)@RequestParam(name="id",required=true) Long id,
            @ApiParam(value = "权限类型:0、负责人权限(读写)1、读写权限2、只读权限",required=true,example="2") @RequestParam(value = "power", required=true)Integer power) {
        
        CrmTeamUser followTeamUser = crmTeamUserService.findById(id);
        if(followTeamUser == null)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        if(ModuleType.business.code != followTeamUser.getTargetType())
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION);
        
        if(TeamUserPower.owner.code == followTeamUser.getPower())
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.teamUser_owner_edit_error);
        
        Business business = businessService.findById(followTeamUser.getTargetId());
        if(business == null || business.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        List<Long> ownerUserIds = Arrays.asList(business.getOwnerUserId(),business.getCownerUserId());
        //校验权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.business, business.getId(), ownerUserIds, CrmResultDefineMsg.teamUser_edit_permission_error);
        
        //不能编辑为负责人权限
        if(TeamUserPower.readWrite.code != power){
            power = TeamUserPower.read.code;
        }
        int i = crmTeamUserService.updatePower(id, power);
        
        return i > 0 ? ResponseResult.success(): ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:business:editTeamUser') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="移除跟进团队成员")
    @PostMapping("/followTeamUser/remove")
    public ResponseResult<Object> removeTeamUser(
            @ApiParam(value="团队成员关系Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        List<CrmTeamUser> followTeamUsers = crmTeamUserService.findByIds(ids);
        if(CollUtil.isNotEmpty(followTeamUsers)){
            Long businessId = followTeamUsers.get(0).getId();
            Business business = businessService.findById(businessId);
            if(business == null || business.getDeltag() == 1)
                throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
            
            List<Long> ownerUserIds = Arrays.asList(business.getOwnerUserId(),business.getCownerUserId());
            //校验权限
            dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.business, business.getId(), ownerUserIds, CrmResultDefineMsg.teamUser_delete_permission_error);
            
            for (CrmTeamUser followTeamUser : followTeamUsers) {
                if(!business.getId().equals(followTeamUser.getTargetId())){
                    throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION);
                }
                
                if(TeamUserPower.owner.code == followTeamUser.getPower())
                    throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.teamUser_owner_delete_error);
            
                crmTeamUserService.delete(followTeamUser.getId(), currentUserId);
            }
            
        }
        return ResponseResult.success();
    }
    
    @ApiOperation(value="退出跟进团队")
    @ApiImplicitParam(name = "id", value = "商机ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/teamUser/quit/{targetId}")
    public ResponseResult<Object> quitFollowTeam(@PathVariable(name="targetId",required=true) Long targetId){
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        CrmTeamUser followTeamUser = crmTeamUserService.find(targetId, ModuleType.business.code, currentUserId);
        if(followTeamUser == null){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD.code,"不是团队成员,无法退出");
        }
        
        if(TeamUserPower.owner.code == followTeamUser.getPower())
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.teamUser_owner_quit_error);
        
        crmTeamUserService.delete(followTeamUser.getId(), currentUserId);
        
        return ResponseResult.success();
    }
    
}
